package com.mall.czlr.app.aop;

import com.mall.czlr.base.common.ErrorResponse;
import com.mall.czlr.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class ControllerAOP {
    private static long startTime;
    private static long endTime;

    @Pointcut("execution(public * com.mall.czlr.app.controller.*.*(..))")
    public void log() { }

    @Before("log()")
    public void before(JoinPoint joinPoint) {
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            ErrorResponse errorResponse = new ErrorResponse();
            errorResponse.setCode(BaseException.ERROR_IN_REQUEST);
            errorResponse.setMessage("requestAttributes获取失败");
            return;
        }

        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        String requestMethod = request.getMethod();
        Object[] args = joinPoint.getArgs();
        log.info("请求url: {}, 请求方式: {}, 参数: {}", requestURI, requestMethod, args);
    }

    @After("log()")
    public void after() {
        endTime = System.currentTimeMillis() - startTime;
    }

    @AfterReturning(pointcut = "log()", returning = "object")
    public void getAfterReturn(Object object) {
        log.info("本次接口耗时: {}ms, 结果: {}", endTime, object.toString());
    }
}
